<?php

namespace App\Http\Controllers\Home;

use App\User;
use Illuminate\Http\Request;
use Auth;
use DB,Session;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{

    public function login(){
        // 如果已经登录，跳转到首页
        if(Auth::guard('home')->check()){
            return redirect('/');
        }
        return view('home.login');
    }

    //public function doLogin(Request $request){
    //    $return = array();
    //    do{
    //        $username = trim($request->username);
    //        $password = trim($request->password);
    //        if(empty($username) || empty($password)){
    //            $return['code'] = 101;
    //            $return['message'] = '用户名或密码不能为空';
    //            break;
    //        }
    //        $user = User::where('username',$username)->where('password',$password)->first();
    //        if(empty($user)){
    //            $return['code'] = 101;
    //            $return['message'] = '用户名或密码错误';
    //            break;
    //        }
    //        Auth::guard('home')->login($user);
    //        $return['code'] = 0;
    //        $return['message'] = '登录成功';
    //        $return['url'] = url('/');
    //        break;
    //
    //    }while(false);
    //    return json_encode($return);
    //}

    public function doLogin(Requests\Home\LoginRequest $request){
        $username = trim($request->username);
        $password = trim($request->password);
        $user = User::where('username',$username)->where('password',$password)->first();
        if(empty($user)){
            return redirect()->back()->withErrors(['username'=>'用户名密码错误'])->withInput();
        }
        Auth::guard('home')->login($user);
        return redirect('/');
    }


    public function reg(){
        return view('home.reg');
    }

    public function doReg(Requests\Home\RegRequest $request){
        $name = trim($request->name);
        $mobile = trim($request->mobile);
        $code = trim($request->code);
        $card_pwd = trim($request->card_pwd);
        $username = trim($request->username);
        $password = trim($request->password);

        $user = User::where('username',$username)->first();
        if(!empty($user)){
            return redirect()->back()->withErrors(['账号已经存在！'])->withInput();
        }
        $user = new User();
        $user->name = $name;
        $user->mobile = $mobile;
        $user->code = $code;
        $user->card_pwd = $card_pwd;
        $user->username = $username;
        $user->password = $password;
        $user->save();
        return redirect('login');

    }





}
